// pages/finance/profile/template/template.js
const fixedTemplate = require('../../../../utils/finance-fixed-template');
const { formatDateTime } = require('../../../../utils/date');
Page({
  data: {
    templateList: [],
    limit: 10,
    templateName: '',
    accountList: [],
    accountIndex: 0,
    showAccountSelector: false,
    financeTypeOptions: [
      { label: '支出', value: 'expense' },
      { label: '收入', value: 'income' }
    ],
    financeTypeIndex: 0,
    categoryList: [],
    categoryIndex: 0,
    paymentList: [],
    paymentIndex: 0,
    cycleDayOptions: Array.from({ length: 31 }, (_, i) => i + 1),
    cycleDayIndex: 0,
    submitting: false,
    editMode: false,
    editId: '',
    cycleDayTip: '',
    showCategoryModal: false,
    incomeCategoryList: [],
    expenseCategoryList: [],
    amount: '',
    showRecordIndex: -1,
    recordList: [],
    startDate: '',
    endDate: '',
  },
  async onLoad() {
    await this.initData();
  },
  async initData() {
    wx.showLoading({ title: '加载中...' });
    try {
      const res = await fixedTemplate.templeteInit();
      // 分类按类型分组
      let incomeCategoryList = [];
      let expenseCategoryList = [];
      if (Array.isArray(res.categoryList)) {
        incomeCategoryList = res.categoryList.filter(item => item.type === 'income');
        expenseCategoryList = res.categoryList.filter(item => item.type === 'expense');
      }
      // 在设置 templateList 前处理
      const accountMap = {};
      (res.accountList || []).forEach(a => { accountMap[a.id] = a.name; });
      const templateList = (res.list || []).map(item => ({
        ...item,
        accountName: accountMap[item.accountBookId] || '账户'
      }));
      this.setData({
        templateList,
        limit: res.limit || 10,
        templateName: '',
        accountList: res.accountList || [],
        accountIndex: 0,
        financeTypeIndex: 0,
        categoryList: res.categoryList || [],
        incomeCategoryList,
        expenseCategoryList,
        categoryIndex: 0,
        paymentList: res.paymentList || [],
        paymentIndex: 0,
        cycleDayIndex: 0,
        submitting: false,
        editMode: false,
        editId: '',
        cycleDayTip: '',
        showCategoryModal: false,
        amount: '',
        startDate: '',
        endDate: ''
      });
    } catch (e) {
      wx.showToast({ title: '加载失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },
  onTemplateNameInput(e) {
    const val = e.detail.value.slice(0, 20);
    this.setData({ templateName: val });
  },
  showAccountSelector() {
    this.setData({ showAccountSelector: true });
  },
  hideAccountSelector() {
    this.setData({ showAccountSelector: false });
  },
  onSelectAccount(e) {
    const idx = e.detail.index;
    this.setData({ accountIndex: idx, showAccountSelector: false });
  },
  // 切换记账类型
  onFinanceTypeChange(e) {
    const idx = e.detail.value;
    let categoryList = idx === 0 ? this.data.expenseCategoryList : this.data.incomeCategoryList;
    this.setData({
      financeTypeIndex: idx,
      categoryList,
      categoryIndex: 0
    });
  },
  // 分类选择按钮点击
  showCategoryModal() {
    let typeIndex = this.data.financeTypeIndex === 0 ? 2 : 1;
    let categoryList = this.data.financeTypeIndex === 0 ? this.data.expenseCategoryList : this.data.incomeCategoryList;
    this.setData({ showCategoryModal: true, categorySelectorTypeIndex: typeIndex, categoryList });
  },
  onCategoryModalClose() {
    this.setData({ showCategoryModal: false });
  },
  onCategorySelect(e) {
    const { index } = e.detail;
    let categoryList = this.data.financeTypeIndex === 0 ? this.data.expenseCategoryList : this.data.incomeCategoryList;
    this.setData({
      categoryIndex: index,
      categoryList,
      showCategoryModal: false
    });
  },
  onPaymentChange(e) {
    this.setData({ paymentIndex: e.detail.value });
  },
  onCycleDayChange(e) {
    const idx = e.detail.value;
    let tip = '';
    if (this.data.cycleDayOptions[idx] > 28) {
      tip = '如果该月没有该日，将是该月实际最后一天';
    }
    this.setData({ cycleDayIndex: idx, cycleDayTip: tip });
  },
  onAmountInput(e) {
    let value = e.detail.value.replace(/[^\d.]/g, '');
    if (value && !/^\d+(\.\d{0,2})?$/.test(value)) {
      value = value.replace(/(\.\d{2})\d+/, '$1');
    }
    this.setData({ amount: value });
  },
  onStartDateChange(e) {
    this.setData({ startDate: e.detail.value });
  },
  onEndDateChange(e) {
    this.setData({ endDate: e.detail.value });
  },
  async onSubmit() {
    if (this.data.submitting) return;
    const { templateName, amount, accountList, accountIndex, financeTypeOptions, financeTypeIndex, categoryList, categoryIndex, paymentList, paymentIndex, cycleDayOptions, cycleDayIndex, editMode, editId, startDate, endDate } = this.data;
    if (!templateName) return wx.showToast({ title: '请输入模板名称', icon: 'none' });
    if (!amount) return wx.showToast({ title: '请输入金额', icon: 'none' });
    if (isNaN(Number(amount)) || Number(amount) <= 0) return wx.showToast({ title: '金额需为正数', icon: 'none' });
    if (!accountList.length) return wx.showToast({ title: '请选择账户', icon: 'none' });
    if (!categoryList.length) return wx.showToast({ title: '请选择分类', icon: 'none' });
    if (!paymentList.length) return wx.showToast({ title: '请选择支付方式', icon: 'none' });
    if (!startDate) return wx.showToast({ title: '请选择开始日期', icon: 'none' });
    if (!endDate) return wx.showToast({ title: '请选择结束日期', icon: 'none' });
    if (endDate < startDate) return wx.showToast({ title: '结束日期不能早于开始日期', icon: 'none' });
    this.setData({ submitting: true });
    const params = {
      templateCode: templateName,
      amount,
      accountBookId: accountList[accountIndex].id,
      financeType: financeTypeOptions[financeTypeIndex].value,
      categoryCode: categoryList[categoryIndex].name,
      paymentMethod: paymentList[paymentIndex].name,
      cycleDay: cycleDayOptions[cycleDayIndex],
      startDate,
      endDate,
    };
    try {
      if (editMode) {
        params.id = editId;
        await fixedTemplate.templeteEdit(params);
        wx.showToast({ title: '编辑成功', icon: 'success' });
      } else {
        await fixedTemplate.templeteAdd(params);
        wx.showToast({ title: '新建成功', icon: 'success' });
      }
      await this.initData();
    } catch (e) {
      wx.showToast({ title: '操作失败', icon: 'none' });
    } finally {
      this.setData({ submitting: false });
    }
  },
  onEditTemplate(e) {
    const idx = e.currentTarget.dataset.index;
    const item = this.data.templateList[idx];
    const accountIdx = this.data.accountList.findIndex(a => a.id === item.accountBookId);
    const typeIdx = this.data.financeTypeOptions.findIndex(t => t.value === item.financeType);
    const categoryIdx = this.data.categoryList.findIndex(c => c.name === item.categoryCode);
    const paymentIdx = this.data.paymentList.findIndex(p => p.name === item.paymentCode);
    const cycleDayIdx = this.data.cycleDayOptions.findIndex(d => d === item.cycleDay);
    this.setData({
      editMode: true,
      editId: item.id,
      templateName: item.templateName,
      accountIndex: accountIdx >= 0 ? accountIdx : 0,
      financeTypeIndex: typeIdx >= 0 ? typeIdx : 0,
      categoryIndex: categoryIdx >= 0 ? categoryIdx : 0,
      paymentIndex: paymentIdx >= 0 ? paymentIdx : 0,
      cycleDayIndex: cycleDayIdx >= 0 ? cycleDayIdx : 0,
      cycleDayTip: (item.cycleDay > 28) ? '如果该月没有该日，将是该月实际最后一天' : '',
      amount: item.amount,
      startDate: item.startDate,
      endDate: item.endDate
    });
  },
  async onDeleteTemplate(e) {
    const idx = e.currentTarget.dataset.index;
    const item = this.data.templateList[idx];
    wx.showModal({
      title: '删除模板',
      content: '确定要删除该模板吗？',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' });
          try {
            await fixedTemplate.templetetDelete(item.id);
            wx.showToast({ title: '删除成功', icon: 'success' });
            await this.initData();
          } catch (e) {
            wx.showToast({ title: '删除失败', icon: 'none' });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  },
  onResetForm() {
    this.setData({
      editMode: false,
      editId: '',
      templateName: '',
      accountIndex: 0,
      financeTypeIndex: 0,
      categoryIndex: 0,
      paymentIndex: 0,
      cycleDayIndex: 0,
      cycleDayTip: '',
      amount: 0.00,
    });
  },
  async onShowRecordList(e) {
    const index = e.currentTarget.dataset.index;
    if (this.data.showRecordIndex === index) {
      // 再次点击收起
      this.setData({ showRecordIndex: -1, recordList: [] });
      return;
    }
    const templateId = this.data.templateList[index].id;
    wx.showLoading({ title: '加载记录...' });
    try {
      const res = await fixedTemplate.recordList(templateId);
      // 先对recordList里面的数据进行遍历，修改后
      const recordList = (Array.isArray(res) ? res: []).map(item => ({
        execTime: formatDateTime(item.execTime),
        result: item.successFlag === 'yes' ? '成功' : '失败',
        errorMsg: item.errorMsg,
        financeRecordId: item.financeRecordId
      }));
      this.setData({
        showRecordIndex: index,
        recordList
      });
    } catch (e) {
      console.error("获取记录失败:", e);
      wx.showToast({ title: '获取记录失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },
  async onRecordCardTap(e) {
    e.stopPropagation && e.stopPropagation();
    const id = e.currentTarget.dataset.id;
    if (!id) return;
    wx.navigateTo({
      url: `/pages/finance/write/write?id=${id}`
    });
  },
  noop() {},
});